<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:og="http://ogp.me/ns#" xmlns:fb="http://www.facebook.com/2008/fbml">

<head>
	<meta charset="UTF-8">
	<title>MakeCode Maker - Blocks / Javascript editor - MakeCode Maker (Cortex class)</title>
	<meta name="Description" content="A Blocks / JavaScript code editor for MakeCode Maker Boards" />

	
<!-- include meta.html -->
<!-- This file is typically overriden by the target, with own Twitter
     account etc. Most data is taken from the theme file though.  
  -->

<!-- include robotsmeta.html -->

<!-- end include robotsmeta.html -->

<meta name="twitter:card" content="summary" />
<meta name="twitter:site" content="@msmakecode" />
<meta name="twitter:title" content="MakeCode Maker - Blocks / Javascript editor - MakeCode Maker (Cortex class)" />
<meta name="twitter:description" content="A Blocks / JavaScript code editor for MakeCode Maker Boards" />
<meta name="twitter:image" content="" />

<meta property="og:title" content="MakeCode Maker - Blocks / Javascript editor - MakeCode Maker (Cortex class)" />
<meta property="og:site_name" content="Microsoft MakeCode" />
<meta property="og:type" content="website" />
<meta property="og:description" content="A Blocks / JavaScript code editor for MakeCode Maker Boards" />
<meta property="fb:app_id" content="" />
<meta property="og:image" content="" />

<meta name="format-detection" content="telephone=no">
<link rel="apple-touch-icon" href="">
<link rel="icon" type="image/png" href="">
<link rel="shortcut icon" href="">
<meta name="theme-color" content="#ecf0f1">

<!-- end include meta.html -->

	
<!-- include head.html -->
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width,height=device-height,user-scalable=no,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0">

<link rel="stylesheet" data-rtl="/blb/rtlsemantic.css" href="/semantic.css" />
<link id="blocklycss"  data-rtl="/blb/rtlblockly.css" rel="stylesheet" href="/blockly.css" />
<link rel="stylesheet" href="/docfiles/style.css" />
<link rel="stylesheet" href="/docfiles/vs.css" />
<link rel="stylesheet" href="/docfiles/target.css" />

<script src="/jquery.js"></script>

<script src="/embed.js" type="text/javascript"></script>
<script src="/docfiles/docs.js" type="text/javascript"></script>
<script src="/docfiles/target.js" type="text/javascript"></script>

<style>
    
.ui.accent { color: #ecf0f1; }
.ui.inverted.accent { background: #ecf0f1; }

</style>

<!-- end include head.html -->


</head>

<body id='root' class='root'>

	<div id="accessibleMenu" class="ui accessibleMenu borderless fixed menu" role="menubar">
		
            <a href="#maincontent" class="ui item link" tabindex="0" role="menuitem">Skip to main content</a>
        
	</div>


	
<!-- include tocheader.html -->
<div class="ui vertical accent lighttoc sidebar menu left hideprint">
    <div class="item">
        <a href="/docs/.html" class="header focused" tabindex="0" title="Go to editor">
            <img aria-hidden="true" role="presentation" class="ui mini image" src="docs/static/logo.svg" />
        </a>
        Documentation
    </div>
    <div class="item search">
        <form id="tocsearch1" role="form" method="get" action="https://www.bing.com/search">
            <div class="ui fluid icon input">
                <input type="hidden" name="q1" value="site:https://maker.makecode.com/" />
                
                <input type="search" name="q" placeholder="Search..." aria-label="Search Documentation">
                <i onclick="document.getElementById('tocsearch1').submit();" tabindex="0" class="search link icon" aria-label="Search" role="button"></i>
            
            </div>
        </form>
    </div>
    <!-- TOC Menu -->
    <div class="menuContainer">
        
    <a class="item " href="/docs/about.html" role="menuitem">About</a>


    <a class="item " href="/docs/faq.html" role="menuitem">FAQ</a>


    <div class="item" title="">
        <a class="header " href="/docs/reference.html" role="menu">Reference</a>
        <div class="menu">
            
    <a class="item " href="/docs/reference/music.html" role="menuitem">music</a>


    <a class="item " href="/docs/reference/pins.html" role="menuitem">pins</a>


    <a class="item " href="/docs/reference/control.html" role="menuitem">control</a>


    <a class="item " href="/docs/reference/serial.html" role="menuitem">serial</a>

        </div>
    </div>


    <div class="item" title="">
        <a class="header " href="/docs/blocks.html" role="menu">Blocks</a>
        <div class="menu">
            
    <a class="item " href="/docs/blocks/on-start.html" role="menuitem">On Start</a>


    <div class="ui  accordion item visible" role="tree" title="">
        <div class=" title">
            <i class="dropdown icon"></i>
            <a class="header" role="treeitem" aria-expanded="false" href="/docs/blocks/loops.html">Loops</a>
        </div>
        <div class=" content">
            
    <a class="item " href="/docs/blocks/loops/repeat.html" role="menuitem">repeat</a>


    <a class="item " href="/docs/blocks/loops/for.html" role="menuitem">for</a>


    <a class="item " href="/docs/blocks/loops/while.html" role="menuitem">while</a>

        </div>
    </div>


    <div class="ui  accordion item visible" role="tree" title="">
        <div class=" title">
            <i class="dropdown icon"></i>
            <a class="header" role="treeitem" aria-expanded="false" href="/docs/blocks/logic.html">Logic</a>
        </div>
        <div class=" content">
            
    <a class="item " href="/docs/blocks/logic/if.html" role="menuitem">if</a>


    <a class="item " href="/docs/blocks/logic/boolean.html" role="menuitem">Boolean</a>

        </div>
    </div>


    <div class="ui  accordion item visible" role="tree" title="">
        <div class=" title">
            <i class="dropdown icon"></i>
            <a class="header" role="treeitem" aria-expanded="false" href="/docs/blocks/variables.html">Variables</a>
        </div>
        <div class=" content">
            
    <a class="item " href="/docs/blocks/variables/assign.html" role="menuitem">assign</a>


    <a class="item " href="/docs/blocks/variables/change.html" role="menuitem">change var</a>


    <a class="item " href="/docs/blocks/variables/var.html" role="menuitem">var</a>

        </div>
    </div>


    <a class="item " href="/docs/blocks/math.html" role="menuitem">Math</a>


    <a class="item " href="/docs/blocks/javascript-blocks.html" role="menuitem">JavaScript blocks</a>


    <a class="item " href="/docs/blocks/custom.html" role="menuitem">Custom blocks</a>

        </div>
    </div>


    <div class="item" title="">
        <a class="header " href="/docs/javascript.html" role="menu">JavaScript</a>
        <div class="menu">
            
    <a class="item " href="/docs/javascript/call.html" role="menuitem">Calling</a>


    <a class="item " href="/docs/javascript/sequence.html" role="menuitem">Sequencing</a>


    <a class="item " href="/docs/javascript/variables.html" role="menuitem">Variables</a>


    <a class="item " href="/docs/javascript/operators.html" role="menuitem">Operators</a>


    <a class="item " href="/docs/javascript/statements.html" role="menuitem">Statements</a>


    <a class="item " href="/docs/javascript/functions.html" role="menuitem">Functions</a>


    <a class="item " href="/docs/javascript/types.html" role="menuitem">Types</a>


    <a class="item " href="/docs/javascript/classes.html" role="menuitem">Classes</a>


    <a class="item " href="/docs/javascript/interfaces.html" role="menuitem">Interfaces</a>


    <a class="item " href="/docs/javascript/generics.html" role="menuitem">Generics</a>

        </div>
    </div>


    <div class="item" title="">
        <a class="header " href="/docs/types.html" role="menu">Types</a>
        <div class="menu">
            
    <a class="item " href="/docs/types/number.html" role="menuitem">Number</a>


    <a class="item " href="/docs/types/string.html" role="menuitem">String</a>


    <a class="item " href="/docs/types/boolean.html" role="menuitem">Boolean</a>


    <a class="item " href="/docs/types/array.html" role="menuitem">Array</a>


    <a class="item " href="/docs/types/function.html" role="menuitem">Function</a>

        </div>
    </div>



    </div>
</div>

<div class="ui fixed accent borderless lighttoc main menu hideprint">
  <div class="ui container">
    
            <a id="togglesidebar" class="launch icon item" tabindex="0" title="Side menu" aria-label="Side menu" role="menu" aria-expanded="false">
                <i class="content icon"></i>
            </a>
        

    <div class="item">
        
    </div>
    
    <div class="right menu">
        <a href="/docs/.html" class="header item" tabindex="0" title="Go to editor">
            <img aria-hidden="true" role="presentation" class="ui mini image" src="docs/static/logo.svg" />
        </a>
    </div>
  </div>
</div>
<!-- end include tocheader.html -->


	<div id="docs" class="pusher">

		
<!-- include toc.html -->
<div class="toc ui accent lighttoc hideprint">
    <div class="ui vertical accent lighttoc sticky menu tocmenu">
        <div class="item">
            <a href="/docs/.html" class="header focused" tabindex="0" title="Go to editor">
                <img aria-hidden="true" role="presentation" class="ui mini image" src="docs/static/logo.svg" />
            </a>
            Documentation
        </div>
        <div class="item search">
            <form id="tocsearch2" role="form" method="get" target="_blank" action="https://www.bing.com/search">
                <div class="ui fluid icon input">
                    <input type="hidden" name="q1" value="site:https://maker.makecode.com/" />
                    
                <input type="search" name="q" placeholder="Search..." aria-label="Search Documentation">
                <i onclick="document.getElementById('tocsearch2').submit();" tabindex="0" class="search link icon" aria-label="Search" role="button"></i>
            
                </div>
            </form>
        </div>
        <!-- TOC Menu -->
        <div class="menuContainer">
            
    <a class="item " href="/docs/about.html" role="menuitem">About</a>


    <a class="item " href="/docs/faq.html" role="menuitem">FAQ</a>


    <div class="item" title="">
        <a class="header " href="/docs/reference.html" role="menu">Reference</a>
        <div class="menu">
            
    <a class="item " href="/docs/reference/music.html" role="menuitem">music</a>


    <a class="item " href="/docs/reference/pins.html" role="menuitem">pins</a>


    <a class="item " href="/docs/reference/control.html" role="menuitem">control</a>


    <a class="item " href="/docs/reference/serial.html" role="menuitem">serial</a>

        </div>
    </div>


    <div class="item" title="">
        <a class="header " href="/docs/blocks.html" role="menu">Blocks</a>
        <div class="menu">
            
    <a class="item " href="/docs/blocks/on-start.html" role="menuitem">On Start</a>


    <div class="ui  accordion item visible" role="tree" title="">
        <div class=" title">
            <i class="dropdown icon"></i>
            <a class="header" role="treeitem" aria-expanded="false" href="/docs/blocks/loops.html">Loops</a>
        </div>
        <div class=" content">
            
    <a class="item " href="/docs/blocks/loops/repeat.html" role="menuitem">repeat</a>


    <a class="item " href="/docs/blocks/loops/for.html" role="menuitem">for</a>


    <a class="item " href="/docs/blocks/loops/while.html" role="menuitem">while</a>

        </div>
    </div>


    <div class="ui  accordion item visible" role="tree" title="">
        <div class=" title">
            <i class="dropdown icon"></i>
            <a class="header" role="treeitem" aria-expanded="false" href="/docs/blocks/logic.html">Logic</a>
        </div>
        <div class=" content">
            
    <a class="item " href="/docs/blocks/logic/if.html" role="menuitem">if</a>


    <a class="item " href="/docs/blocks/logic/boolean.html" role="menuitem">Boolean</a>

        </div>
    </div>


    <div class="ui  accordion item visible" role="tree" title="">
        <div class=" title">
            <i class="dropdown icon"></i>
            <a class="header" role="treeitem" aria-expanded="false" href="/docs/blocks/variables.html">Variables</a>
        </div>
        <div class=" content">
            
    <a class="item " href="/docs/blocks/variables/assign.html" role="menuitem">assign</a>


    <a class="item " href="/docs/blocks/variables/change.html" role="menuitem">change var</a>


    <a class="item " href="/docs/blocks/variables/var.html" role="menuitem">var</a>

        </div>
    </div>


    <a class="item " href="/docs/blocks/math.html" role="menuitem">Math</a>


    <a class="item " href="/docs/blocks/javascript-blocks.html" role="menuitem">JavaScript blocks</a>


    <a class="item " href="/docs/blocks/custom.html" role="menuitem">Custom blocks</a>

        </div>
    </div>


    <div class="item" title="">
        <a class="header " href="/docs/javascript.html" role="menu">JavaScript</a>
        <div class="menu">
            
    <a class="item " href="/docs/javascript/call.html" role="menuitem">Calling</a>


    <a class="item " href="/docs/javascript/sequence.html" role="menuitem">Sequencing</a>


    <a class="item " href="/docs/javascript/variables.html" role="menuitem">Variables</a>


    <a class="item " href="/docs/javascript/operators.html" role="menuitem">Operators</a>


    <a class="item " href="/docs/javascript/statements.html" role="menuitem">Statements</a>


    <a class="item " href="/docs/javascript/functions.html" role="menuitem">Functions</a>


    <a class="item " href="/docs/javascript/types.html" role="menuitem">Types</a>


    <a class="item " href="/docs/javascript/classes.html" role="menuitem">Classes</a>


    <a class="item " href="/docs/javascript/interfaces.html" role="menuitem">Interfaces</a>


    <a class="item " href="/docs/javascript/generics.html" role="menuitem">Generics</a>

        </div>
    </div>


    <div class="item" title="">
        <a class="header " href="/docs/types.html" role="menu">Types</a>
        <div class="menu">
            
    <a class="item " href="/docs/types/number.html" role="menuitem">Number</a>


    <a class="item " href="/docs/types/string.html" role="menuitem">String</a>


    <a class="item " href="/docs/types/boolean.html" role="menuitem">Boolean</a>


    <a class="item " href="/docs/types/array.html" role="menuitem">Array</a>


    <a class="item " href="/docs/types/function.html" role="menuitem">Function</a>

        </div>
    </div>



        </div>
    </div>
</div>
<!-- end include toc.html -->


		<div class="article" id="maincontent">
			<div class="article-inner">

				
<!-- include header.html -->
<div class="ui one column padded grid hideprint hidemobile">
    <div class="column">
        
    </div>
</div>

<!-- end include header.html -->


				<div class="main ui container fluid mainbody">
					
            <button id="printbtn" class="circular ui icon right floated button hideprint" title="Print this page">
                <i class="icon print"></i>
            </button>
         
    <div class="ui text">
        <h1 id="generics">Generics</h1><p>A major part of software engineering is building components that not only have well-defined and consistent APIs, but are also reusable.
Components that are capable of working on the data of today as well as the data of tomorrow will give you the most flexible capabilities for building up large software systems.</p>
<p>In languages like C# and Java, one of the main tools in the toolbox for creating reusable components is <em>generics</em>, that is, being able to create a component that can work over a variety of types rather than a single one.
This allows users to consume these components and use their own types.</p>
<h2 id="hello-world-of-generics">Hello World of Generics</h2><p>To start off, let’s do the “hello world” of generics: the identity function.
The identity function is a function that will return back whatever is passed in.
You can think of this in a similar way to the <code>echo</code> command.</p>
<p>Without generics, we would either have to give the identity function a specific type:</p>
<pre><code class="lang-ts">function identity(arg: number): number {
    return arg;
}</code></pre>
<p>We need a way of capturing the type of the argument in such a way that we can also use it to denote what is being returned.
Here, we will use a <em>type variable</em>, a special kind of variable that works on types rather than values.</p>
<pre><code class="lang-ts">function identity&lt;T&gt;(arg: T): T {
    return arg;
}</code></pre>
<p>We’ve now added a type variable <code>T</code> to the identity function.
This <code>T</code> allows us to capture the type the user provides (e.g. <code>number</code>), so that we can use that information later.
Here, we use <code>T</code> again as the return type. On inspection, we can now see the same type is used for the argument and the return type.
This allows us to traffic that type information in one side of the function and out the other.</p>
<p>We say that this version of the <code>identity</code> function is generic, as it works over a range of types.
Once we’ve written the generic identity function, we can call it in one of two ways.
The first way is to pass all of the arguments, including the type argument, to the function:</p>
<pre><code class="lang-ts">let output = identity&lt;string&gt;(&quot;myString&quot;);  // type of output will be &#39;string&#39;</code></pre>
<p>Here we explicitly set <code>T</code> to be <code>string</code> as one of the arguments to the function call, denoted using the <code>&lt;&gt;</code> around the arguments rather than <code>()</code>.</p>
<p>The second way is also perhaps the most common. Here we use <em>type argument inference</em> – that is, we want the compiler to set the value of <code>T</code> for us automatically based on the type of the argument we pass in:</p>
<pre><code class="lang-ts">let output = identity(&quot;myString&quot;);  // type of output will be &#39;string&#39;</code></pre>
<p>Notice that we didn’t have to explicitly pass the type in the angle brackets (<code>&lt;&gt;</code>); the compiler just looked at the value <code>&quot;myString&quot;</code>, and set <code>T</code> to its type.
While type argument inference can be a helpful tool to keep code shorter and more readable, you may need to explicitly pass in the type arguments as we did in the previous example when the compiler fails to infer the type, as may happen in more complex examples.</p>
<h2 id="working-with-generic-type-variables">Working with Generic Type Variables</h2><p>When you begin to use generics, you’ll notice that when you create generic functions like <code>identity</code>, the compiler will enforce that you use any generically typed parameters in the body of the function correctly.
That is, that you actually treat these parameters as if they could be any and all types.</p>
<p>Let’s take our <code>identity</code> function from earlier:</p>
<pre><code class="lang-ts">function identity&lt;T&gt;(arg: T): T {
    return arg;
}</code></pre>
<p>What if we want to also log the length of the argument <code>arg</code> to the console with each call?
We might be tempted to write this:</p>
<pre><code class="lang-ts">function loggingIdentity&lt;T&gt;(arg: T): T {
    console.log(arg.length.toString());  // Error: T doesn&#39;t have .length
    return arg;
}</code></pre>
<p>When we do, the compiler will give us an error that we’re using the <code>.length</code> member of <code>arg</code>, but nowhere have we said that <code>arg</code> has this member.
Remember, we said earlier that these type variables stand in for any and all types, so someone using this function could have passed in a <code>number</code> instead, which does not have a <code>.length</code> member.</p>
<p>Let’s say that we’ve actually intended this function to work on arrays of <code>T</code> rather than <code>T</code> directly. Since we’re working with arrays, the <code>.length</code> member should be available.
We can describe this just like we would create arrays of other types:</p>
<pre><code class="lang-ts">function loggingIdentity&lt;T&gt;(arg: T[]): T[] {
    console.log(arg.length.toString());  // Array has a .length, so no more error
    return arg;
}</code></pre>
<p>You can read the type of <code>loggingIdentity</code> as “the generic function <code>loggingIdentity</code> takes a type parameter <code>T</code>, and an argument <code>arg</code> which is an array of <code>T</code>s, and returns an array of <code>T</code>s.”
If we passed in an array of numbers, we’d get an array of numbers back out, as <code>T</code> would bind to <code>number</code>.
This allows us to use our generic type variable <code>T</code> as part of the types we’re working with, rather than the whole type, giving us greater flexibility.</p>
<p>We can alternatively write the sample example this way:</p>
<pre><code class="lang-ts">function loggingIdentity&lt;T&gt;(arg: Array&lt;T&gt;): Array&lt;T&gt; {
    console.log(arg.length.toString());  // Array has a .length, so no more error
    return arg;
}</code></pre>
<p>You may already be familiar with this style of type from other languages.
In the next section, we’ll cover how you can create your own generic types like <code>Array&lt;T&gt;</code>.</p>
<h2 id="generic-types">Generic Types</h2>
    <div class="ui info message">
        <div class="content">
            <p>Static TypeScript does not currently support generic functions as values.</p>

        </div>
    </div>
<p>In previous sections, we created generic identity functions that worked over a range of types.
In this section, we’ll explore the type of the functions themselves and how to create generic interfaces.</p>
<p>The type of generic functions is just like those of non-generic functions, with the type parameters listed first, similarly to function declarations:</p>
<pre><code class="lang-ts">function identity&lt;T&gt;(arg: T): T {
    return arg;
}

let myIdentity: &lt;T&gt;(arg: T) =&gt; T = identity;</code></pre>
<p>We could also have used a different name for the generic type parameter in the type, so long as the number of type variables and how the type variables are used line up.</p>
<pre><code class="lang-ts">function identity&lt;T&gt;(arg: T): T {
    return arg;
}

let myIdentity: &lt;U&gt;(arg: U) =&gt; U = identity;</code></pre>
<p>We can also write the generic type as a call signature of an object literal type:</p>
<pre><code class="lang-ts">function identity&lt;T&gt;(arg: T): T {
    return arg;
}

let myIdentity: {&lt;T&gt;(arg: T): T} = identity;</code></pre>
<p>Which leads us to writing our first generic interface.
Let’s take the object literal from the previous example and move it to an interface:</p>
<pre><code class="lang-ts">interface GenericIdentityFn {
    &lt;T&gt;(arg: T): T;
}

function identity&lt;T&gt;(arg: T): T {
    return arg;
}

let myIdentity: GenericIdentityFn = identity;</code></pre>
<p>In a similar example, we may want to move the generic parameter to be a parameter of the whole interface.
This lets us see what type(s) we’re generic over (e.g. <code>Dictionary&lt;string&gt;</code> rather than just <code>Dictionary</code>).
This makes the type parameter visible to all the other members of the interface.</p>
<pre><code class="lang-ts">interface GenericIdentityFn&lt;T&gt; {
    (arg: T): T;
}

function identity&lt;T&gt;(arg: T): T {
    return arg;
}

let myIdentity: GenericIdentityFn&lt;number&gt; = identity;</code></pre>
<p>Notice that our example has changed to be something slightly different.
Instead of describing a generic function, we now have a non-generic function signature that is a part of a generic type.
When we use <code>GenericIdentityFn</code>, we now will also need to specify the corresponding type argument (here: <code>number</code>), effectively locking in what the underlying call signature will use.
Understanding when to put the type parameter directly on the call signature and when to put it on the interface itself will be helpful in describing what aspects of a type are generic.</p>
<p>In addition to generic interfaces, we can also create generic classes.
Note that it is not possible to create generic enums and namespaces.</p>
<h2 id="generic-classes">Generic Classes</h2><p>A generic class has a similar shape to a generic interface.
Generic classes have a generic type parameter list in angle brackets (<code>&lt;&gt;</code>) following the name of the class.</p>
<pre><code class="lang-ts">class GenericNumber&lt;T&gt; {
    zeroValue: T;
    add: (x: T, y: T) =&gt; T;
}

let myGenericNumber = new GenericNumber&lt;number&gt;();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x, y) { return x + y; };</code></pre>
<p>This is a pretty literal use of the <code>GenericNumber</code> class, but you may have noticed that nothing is restricting it to only use the <code>number</code> type.
We could have instead used <code>string</code> or even more complex objects.</p>
<pre><code class="lang-ts">class GenericNumber&lt;T&gt; {
    zeroValue: T;
    add: (x: T, y: T) =&gt; T;
}

let stringNumeric = new GenericNumber&lt;string&gt;();
stringNumeric.zeroValue = &quot;&quot;;
stringNumeric.add = function (x, y) { return x + y; };

console.log(stringNumeric.add(stringNumeric.zeroValue, &quot;test&quot;));</code></pre>
<p>Just as with interface, putting the type parameter on the class itself lets us make sure all of the properties of the class are working with the same type.</p>
<h2 id="generic-constraints">Generic Constraints</h2><p>If you remember from an earlier example, you may sometimes want to write a generic function that works on a set of types where you have some knowledge about what capabilities that set of types will have.
In our <code>loggingIdentity</code> example, we wanted to be able to access the <code>.length</code> property of <code>arg</code>, but the compiler could not prove that every type had a <code>.length</code> property, so it warns us that we can’t make this assumption.</p>
<pre><code class="lang-ts">function loggingIdentity&lt;T&gt;(arg: T): T {
    console.log(arg.length.toString());  // Error: T doesn&#39;t have .length
    return arg;
}</code></pre>
<p>Instead of working with any and all types, we’d like to constrain this function to work with any and 
all types that also have the <code>.length</code> property.
As long as the type has this member, we’ll allow it, but it’s required to have at least this member.
To do so, we must list our requirement as a constraint on what T can be.</p>
<p>To do so, we’ll create an interface that describes our constraint.
Here, we’ll create an interface that has a single <code>.length</code> property and then we’ll use this interface and the <code>extends</code> keyword to denote our constraint:</p>
<pre><code class="lang-ts">interface Lengthwise {
    length: number;
}

function loggingIdentity&lt;T extends Lengthwise&gt;(arg: T): T {
    console.log(arg.length.toString());  // Now we know it has a .length property, so no more error
    return arg;
}</code></pre>
<p>Because the generic function is now constrained, it will no longer work over any and all types:</p>
<pre><code class="lang-ts">loggingIdentity(3);  // Error, number doesn&#39;t have a .length property</code></pre>
<p>Instead, we need to pass in values whose type has all the required properties:</p>
<pre><code class="lang-ts">loggingIdentity({length: 10, value: 3});</code></pre>

    </div>

					<div class="hideprint"></div>
				</div>

				
<!-- include footer.html -->
<footer class="ui vertical footer segment hideprint" aria-hidden="false">
    <div class="ui center aligned container">
        <div class="ui horizontal link list">
            <a class="item" href="https://twitter.com/intent/follow?screen_name=MsMakeCode" title="Follow us on Twitter" target="_blank"
                rel="noopener">
                <i class="huge icon twitter"></i>
            </a>
            <a class="item" href="https://www.instagram.com/makecode/" title="Follow us on Instagram" target="_blank" rel="noopened">
                <i class="huge icon instagram"></i>
            </a>
            <a class="item" href="https://www.youtube.com/channel/UCye7YlvFUUQ1dSy0WZZ1T_Q" title="Subscribe to our YouTube channel"
                target="_blank" rel="noopened">
                <i class="huge icon youtube"></i>
            </a>
            <a class="item" href="mailto:makecode@microsoft.com" title="Send us an Email" rel="noopened">
                <i class="huge icon mail"></i>
            </a>
        </div>
        <div class="ui section divider"></div>
        <div class="ui container horizontal small divided link list">
            <!-- <a class="item" href="https://makecode.com/contact" target="_blank" rel="noopener">Contact Us</a> -->
            <a class="item" href="https://makecode.com/privacy" target="_blank" rel="noopener">Privacy &amp; Cookies</a>
            <a class="item" href="https://makecode.com/termsofuse" target="_blank" rel="noopener"> Terms Of Use</a>
            <a class="item" href="https://makecode.com/trademarks" target="_blank" rel="noopener">Trademarks</a>
            <div class="item">© 2018 Microsoft</div>
        </div>
        <div class="ui container horizontal small divided link list">
            <a class="ui centered item" href="https://makecode.com/" title="Microsoft MakeCode" target="_blank" rel="noopener">Powered by Microsoft MakeCode</a>
        </div>
    </div>
</footer>

<!-- end include footer.html -->

			</div>

		</div>

	</div>


	
<!-- include macros.html -->
<!-- macro button -->

<!-- macro vimeo -->

<!-- macro youtube -->

<!-- macro section -->

<!-- macro hide -->

<!-- macro avatar -->

<!-- macro hint -->

<!-- wrapped around ordinary content -->
<!-- macro main-container -->

<!-- used for 'column' box - they are collected and wrapped in 'column-container' -->
<!-- macro column -->
<!-- macro column-container -->


<!-- Menu on the top of the page -->
<!-- macro item -->

<!-- macro divider -->

<!-- macro top-dropdown -->

<!-- macro inner-dropdown -->


<!-- TOC in the sidebar -->
<!-- macro item -->

<!-- macro divider -->

<!-- macro top-dropdown -->

<!-- macro top-dropdown-noheading -->

<!-- macro inner-dropdown -->

<!-- macro nested-dropdown -->

<!-- end include macros.html -->

	
<!-- include tracking.html -->
<script type="text/javascript" src="/pxtweb.js"></script>
<script type="text/javascript">
    window.loadAppInsights = function (includeCookie) {
        var appInsights=window.appInsights||function(config){
            function i(config){t[config]=function(){var i=arguments;t.queue.push(function(){t[config].apply(t,i)})}}var t={config:config},u=document,e=window,o="script",s="AuthenticatedUserContext",h="start",c="stop",l="Track",a=l+"Event",v=l+"Page",y=u.createElement(o),r,f;y.src=config.url||"https://az416426.vo.msecnd.net/scripts/a/ai.0.js";u.getElementsByTagName(o)[0].parentNode.appendChild(y);try{t.cookie=u.cookie}catch(p){}for(t.queue=[],t.version="1.0",r=["Event","Exception","Metric","PageView","Trace","Dependency"];r.length;)i("track"+r.pop());return i("set"+s),i("clear"+s),i(h+a),i(c+a),i(h+v),i(c+v),i("flush"),config.disableExceptionTracking||(r="onerror",i("_"+r),f=e[r],e[r]=function(config,i,u,e,o){var s=f&&f(config,i,u,e,o);return s!==!0&&t["_"+r](config,i,u,e,o),s}),t
        }({
            instrumentationKey:"9801ed01-c40f-46ec-aa40-2a1742a9e71c",
            disableAjaxTracking: true,
            overridePageViewDuration: false,
            disableExceptionTracking: true,
            isCookieUseDisabled: !includeCookie,
            isStorageUseDisabled: !includeCookie,
            url: "/ai.0.js"
        });
        window.appInsights=appInsights;
        appInsights.queue.push(function () {
            appInsights.context.addTelemetryInitializer(function (envelope) {
                if (typeof pxtConfig === "undefined") return;
                var telemetryItem = envelope.data.baseData;
                telemetryItem.properties = telemetryItem.properties || {};
                telemetryItem.properties["target"] = pxtConfig.targetId;
                telemetryItem.properties["stage"] = (pxtConfig.relprefix || "/--").replace(/[^a-z]/ig, '')
                telemetryItem.properties["cookie"] = includeCookie;
                if (typeof Windows !== "undefined")
                    telemetryItem.properties["WindowsApp"] = 1;
                var userAgent = navigator.userAgent.toLowerCase();
                var userAgentRegexResult = /\belectron\/(\d+\.\d+\.\d+.*?)(?: |$)/i.exec(userAgent); // Example navigator.userAgent: "Mozilla/5.0 Chrome/61.0.3163.100 Electron/2.0.0 Safari/537.36"
                if (userAgentRegexResult) {
                    telemetryItem.properties["Electron"] = 1;
                    telemetryItem.properties["ElectronVersion"] = userAgentRegexResult[1];
                }
                if (typeof pxtElectron !== "undefined") {
                    telemetryItem.properties["PxtElectron"] = 1;
                    telemetryItem.properties["ElectronVersion"] = pxtElectron.versions.electronVersion;
                    telemetryItem.properties["ChromiumVersion"] = pxtElectron.versions.chromiumVersion;
                    telemetryItem.properties["NodeVersion"] = pxtElectron.versions.nodeVersion;
                    telemetryItem.properties["PxtElectronVersion"] = pxtElectron.versions.pxtElectronVersion;
                    telemetryItem.properties["PxtCoreVersion"] = pxtElectron.versions.pxtCoreVersion;
                    telemetryItem.properties["PxtTargetVersion"] = pxtElectron.versions.pxtTargetVersion;
                    telemetryItem.properties["PxtElectronIsProd"] = pxtElectron.versions.isProd;
                }
            });
        });
        appInsights.trackPageView(null, scrubUrl(window.location.toString()), {urlReferrer: scrubUrl(document.referrer.toString())});

        //Scrub the key (if any) from the URL.
        function scrubUrl(url) {
            var scriptIdRegex = /(?:\d{5}-\d{5}-\d{5}-\d{5})|(?:_[0-9a-zA-Z]{12})/g;
            return url.replace(scriptIdRegex, "xxxxx-xxxxx-xxxxx-xxxxx");
        }
    }
    pxt.initAnalyticsAsync();
</script>
<!-- end include tracking.html -->


</body>

</html>